package com.xjscrm.server.service.customer.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.uzai.mobile.collect.api.MicaTopics;
import com.uzai.mobile.collect.api.dto.MicaTriggerDto;
import com.uzai.mobile.collect.api.dto.trigger.MicaTriggerBatchMarkLabelMsg;
import com.uzai.mobile.collect.api.dto.trigger.MicaTriggerChangeLabelMsg;
import com.uzai.mobile.collect.api.enums.MicaTriggerType;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.annotation.MerId;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.enums.DeviceTypeEnum;
import com.xjscrm.common.enums.RedisCacheKeyEnum;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.server.biz.RatelimitService;
import com.xjscrm.server.biz.mq.producer.SendMsgProducer;
import com.xjscrm.server.common.util.DeviceTools;
import com.xjscrm.server.common.util.Functions;
import com.xjscrm.server.constant.Const;
import com.xjscrm.server.dto.wwcustomer.WwCustomerQuery;
import com.xjscrm.server.dto.wwcustomertagsuserid.WwCustomerTagsUseridQuery;
import com.xjscrm.server.dto.wwtagsuserid.WwTagsUseridQuery;
import com.xjscrm.server.mapper.*;
import com.xjscrm.server.service.common.CorpApplicationDeviceService;
import com.xjscrm.server.service.common.CorpApplicationService;
import com.xjscrm.server.service.customer.WwCustomerSyncService;
import com.xjscrm.server.service.device.WwDeviceInfoService;
import com.xjscrm.server.vo.device.Device;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 企业微信客户添加实现类
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class WwCustomerSyncServiceImpl implements WwCustomerSyncService {
    @Autowired
    private WwCustomerMapper wwCustomerMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private WwTagsUseridMapper wwTagsUseridMapper;
    @Autowired
    private WwDeviceMapper wwDeviceMapper;
    @Autowired
    private SendMsgProducer sendMsgProducer;
    @Autowired
    private WwCustomerTagsUseridMapper wwCustomerTagsUseridMapper;
    @Autowired
    private WwCorpMapper wwCorpMapper;
    @Autowired
    private CorpApplicationService corpApplicationService;
    @Autowired
    private WwDeviceInfoService wwDeviceInfoService;

    /**
     * 自动刷新会员的内部账号信息
     *
     * @param merId
     * @return
     */
    @Async("taskExecutorForXxJob")
    @TraceGenerate //注入消息id标签
    public void autoRefreashExternalUserid(@MerId Long merId) {

        //限流key
        String taskLimitKey = "-autoRefreashExternalUserid-taskLimitKey-merId=" + merId;
        Object object = redisTemplate.opsForValue().get(taskLimitKey);
        if (object == null) {
            //保存限流key
            redisTemplate.opsForValue().set(taskLimitKey, taskLimitKey, 300, TimeUnit.SECONDS);
        } else{
            return;
        }

        log.info("--进入给会员刷新内部账号-查询会员添加个人标签线程--merId={}", merId);

        try {
            //查询该运营商是否已经配置企业信息
            List<WwCorp> wwCorpList = wwCorpMapper.selectByMerId(merId);
            if (wwCorpList != null && wwCorpList.size() > 0) {
                for (WwCorp wwCorp : wwCorpList) {
                    //验证企业填写了开放平台资料信息，才能打标签功能
                    CorpApplication corpApplication = corpApplicationService.selectByCorpId(wwCorp.getCorpId());
                    if(corpApplication != null && StringUtils.isNotBlank(corpApplication.getAuthCorpId())
                            && StringUtils.isNotBlank(corpApplication.getPermanentCode())
                            && Tools.getInteger(corpApplication.getStatus()).intValue() == 1
                    ){
                        //查询该企业下的所有机器人列表
                        List<WwDevice> wwDeviceList = wwDeviceInfoService.queryByCorpId(merId, corpApplication.getCorpId());
                        if (wwDeviceList != null && wwDeviceList.size() > 0) {
                            for (WwDevice wwDevice : wwDeviceList) {
                                //验证该机器人是否在线
                                String deviceLastHeatBeatTimeKey = String.format(RedisCacheKeyEnum.WW_DEVICE_LAST_HEAT_BEAT_TIME.getKey(), wwDevice.getDeviceId());
                                Object deviceLastHeatBeatTimeObject = redisTemplate.opsForValue().get(deviceLastHeatBeatTimeKey);
                                if (deviceLastHeatBeatTimeObject != null) { //表示机器人在线，机器人在线才操作

                                    //查询该机器人下已经创建过标签但是还未从微信开放平台回调的标签（控制限流）
                                    WwTagsUseridQuery wwTagsUseridQuery = new WwTagsUseridQuery();
                                    wwTagsUseridQuery.setMerId(wwDevice.getMerId());
                                    wwTagsUseridQuery.setDeviceUniqueId(wwDevice.getId());
                                    Integer count = Tools.getInteger(wwTagsUseridMapper.findCount(wwTagsUseridQuery));
                                    log.info("该机器人的刷新个人内部账号添加的标签未处理总数,deviceUniqueId={}, count={}", wwDevice.getId(), count);
                                    if(count >= 10){
                                        continue;
                                    }

                                    //查询此机器人上次发送时间
                                    String deivceExternalUseridSendTimeKey = String.format(RedisCacheKeyEnum.DEIVCE_EXTERNAL_USERID_SEND_TIME.getKey(), wwDevice.getId());
                                    Object deivceExternalUseridSendTimeObject = redisTemplate.opsForValue().get(deivceExternalUseridSendTimeKey);
                                    if(deivceExternalUseridSendTimeObject != null){//需要判断此机器人发送频率
                                        //查询此机器人上次发送时间
                                        Integer deivceExternalUseridSendTime = (Integer)deivceExternalUseridSendTimeObject;
                                        //发送频率//默认50
                                        Integer deivceExternalUseridRate = 50;
                                        String deivceExternalUseridRateKey = String.format(RedisCacheKeyEnum.DEIVCE_EXTERNAL_USERID_RATE.getKey(), wwDevice.getId());
                                        Object deivceExternalUseridRateObject = redisTemplate.opsForValue().get(deivceExternalUseridRateKey);
                                        if(deivceExternalUseridRateObject != null){
                                            deivceExternalUseridRate = (Integer)deivceExternalUseridRateObject;
                                        }
                                        //如果当前时间-上次发送时间的结果小于发送频率，则表示还未轮到，则跳出循环
                                        if(DateUtil.getTime() - deivceExternalUseridSendTime.intValue() < deivceExternalUseridRate.intValue()){
                                            continue;
                                        }
                                    }

                                    //每个机器人查询10个会员
                                    WwCustomerQuery wwCustomerQuery = new WwCustomerQuery();
                                    wwCustomerQuery.setMerId(wwDevice.getMerId());
                                    wwCustomerQuery.setDeviceUniqueId(wwDevice.getId());
                                    //wwCustomerQuery.setIdStart(customeId);
                                    wwCustomerQuery.setExternalUseridIsNull(1); //查询内部账号为空的
                                    wwCustomerQuery.setExternalStatus(0); //
                                    //查询所有的自动发圈配置记录
                                    Page<WwCustomer> page = new Page<>();
                                    page.setCurrent(1);//只查第一页
                                    page.setSize(10); //每页查询10个
                                    page.addOrder(OrderItem.desc("id"));//默认id降序

                                    List<WwCustomer> wwCustomerList = wwCustomerMapper.findByList(page, wwCustomerQuery);
                                    if (wwCustomerList != null) {
                                        for (WwCustomer wwCustomer : wwCustomerList) {
                                            addTagForExternalUserid(wwDevice, wwCustomer);
                                        }
                                    }

                                    //更新机器人发送外部会员id的频率缓存(5分钟)
                                    redisTemplate.opsForValue().set(deivceExternalUseridSendTimeKey, DateUtil.getTime(), 300, TimeUnit.SECONDS);
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.info(e.getMessage(), e);
        } finally {
            //删除限流key
            redisTemplate.delete(taskLimitKey);
        }
    }

    /**
     * 自动刷新会员的内部账号信息
     *
     * @param merId
     * @return
     */
    @Async("taskExecutorForXxJob")
    @TraceGenerate //注入消息id标签
    public void autoSendExternalUserid(@MerId Long merId) {

        //限流key
        String taskLimitKey = "-autoSendExternalUserid-taskLimitKey-merId=" + merId;
        Object object = redisTemplate.opsForValue().get(taskLimitKey);
        if (object == null) {
            //保存限流key
            redisTemplate.opsForValue().set(taskLimitKey, taskLimitKey, 300, TimeUnit.SECONDS);
        } else {
            return;
        }

        log.info("--进入给会员刷新内部账号-查询会员发送个人标签线程--merId={}", merId);

        try {
            //查询该运营商是否已经配置企业信息
            List<WwCorp> wwCorpList = wwCorpMapper.selectByMerId(merId);
            if (wwCorpList != null && wwCorpList.size() > 0) {
                for (WwCorp wwCorp : wwCorpList) {
                    //验证企业填写了开放平台资料信息，才能打标签功能
                    //验证企业填写了开放平台资料信息，才能打标签功能
                    CorpApplication corpApplication = corpApplicationService.selectByCorpId(wwCorp.getCorpId());
                    if(corpApplication != null && StringUtils.isNotBlank(corpApplication.getAuthCorpId()) && StringUtils.isNotBlank(corpApplication.getPermanentCode())){
                        //查询该企业下的所有机器人列表
                        List<WwDevice> wwDeviceList = wwDeviceInfoService.queryByCorpId(merId, corpApplication.getCorpId());
                        if (wwDeviceList != null && wwDeviceList.size() > 0) {
                            for (WwDevice wwDevice : wwDeviceList) {
                                //验证该机器人是否在线
                                String deviceLastHeatBeatTimeKey = String.format(RedisCacheKeyEnum.WW_DEVICE_LAST_HEAT_BEAT_TIME.getKey(), wwDevice.getDeviceId());
                                Object deviceLastHeatBeatTimeObject = redisTemplate.opsForValue().get(deviceLastHeatBeatTimeKey);
                                if (deviceLastHeatBeatTimeObject != null) { //表示机器人在线，机器人在线才操作
                                    //查询该机器人下已经创建过标签但是还未从微信开放平台回调的标签（控制限流）
                                    WwCustomerTagsUseridQuery wwCustomerTagsUseridQuery = new WwCustomerTagsUseridQuery();
                                    wwCustomerTagsUseridQuery.setMerId(wwDevice.getMerId());
                                    wwCustomerTagsUseridQuery.setDeviceUniqueId(wwDevice.getId());
                                    Integer count = Tools.getInteger(wwCustomerTagsUseridMapper.findCount(wwCustomerTagsUseridQuery));
                                    log.info("该机器人的刷新个人内部账号发送的标签未处理总数,derviceUniqueId={}, count={}", wwDevice.getId(), count);
                                    if(count >= 10){
                                        continue;
                                    }

                                    //每个机器人查询10个已经创建完成的个人标签
                                    WwTagsUseridQuery wwTagsUseridQuery = new WwTagsUseridQuery();
                                    wwTagsUseridQuery.setMerId(wwDevice.getMerId());
                                    wwTagsUseridQuery.setDeviceUniqueId(wwDevice.getId());
                                    wwTagsUseridQuery.setStatus(1); //标签状态（0-不可用，1-可用）
                                    //查询所有的自动发圈配置记录
                                    Page<WwCustomer> page = new Page<>();
                                    page.setCurrent(1);//只查第一页
                                    page.setSize(10); //每页查询10个
                                    page.addOrder(OrderItem.asc("id"));//默认id升序
                                    List<WwTagsUserid> wwTagsUseridList = wwTagsUseridMapper.findByList(page, wwTagsUseridQuery);
                                    if (wwTagsUseridList != null) {
                                        for (WwTagsUserid wwTagsUserid : wwTagsUseridList) {
                                            sendTagForExternalUserid(wwDevice, wwTagsUserid);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.info(e.getMessage(), e);
        } finally {
            //删除限流key
            redisTemplate.delete(taskLimitKey);
        }
    }

    /**
     * 自动刷新会员的内部账号信息-删除过期标签
     *
     * @param merId
     * @return
     */
    @Async("taskExecutorForXxJob")
    @TraceGenerate //注入消息id标签
    public void autoDeleteExternalUserid(@MerId Long merId) {

        //限流key
        String taskLimitKey = "-autoDeleteExternalUserid-taskLimitKey-merId=" + merId;
        Object object = redisTemplate.opsForValue().get(taskLimitKey);
        if (object == null) {
            //保存限流key
            redisTemplate.opsForValue().set(taskLimitKey, taskLimitKey, 300, TimeUnit.SECONDS);
        } else {
            return;
        }

        log.info("--进入给会员刷新内部账号-删除会员发送的过期个人标签线程--merId={}", merId);

        try {
            //查询该运营商是否已经配置企业信息
            List<WwCorp> wwCorpList = wwCorpMapper.selectByMerId(merId);
            if (wwCorpList != null && wwCorpList.size() > 0) {
                for (WwCorp wwCorp : wwCorpList) {
                    //验证企业填写了开放平台资料信息，才能打标签功能
//                    if(StringUtils.isNotBlank(wwCorp.getEntId())
//                            && StringUtils.isNotBlank(wwCorp.getEntSecret())
//                            && StringUtils.isNotBlank(wwCorp.getEntToken())){
                        //查询该企业下的所有机器人列表
                        List<WwDevice> wwDeviceList = wwDeviceMapper.queryByCorpId(wwCorp.getCorpId(), merId);
                        if (wwDeviceList != null && wwDeviceList.size() > 0) {
                            for (WwDevice wwDevice : wwDeviceList) {
                                //验证该机器人是否在线
                                String deviceLastHeatBeatTimeKey = String.format(RedisCacheKeyEnum.WW_DEVICE_LAST_HEAT_BEAT_TIME.getKey(), wwDevice.getDeviceId());
                                Object deviceLastHeatBeatTimeObject = redisTemplate.opsForValue().get(deviceLastHeatBeatTimeKey);
                                if (deviceLastHeatBeatTimeObject != null) { //表示机器人在线，机器人在线才操作

                                    //每个机器人查询10个已经创建完成的个人标签
                                    WwTagsUseridQuery wwTagsUseridQuery = new WwTagsUseridQuery();
                                    wwTagsUseridQuery.setMerId(wwDevice.getMerId());
                                    wwTagsUseridQuery.setDeviceUniqueId(wwDevice.getId());
                                    wwTagsUseridQuery.setCreateTimeEnd(DateUtil.getTime()- 4 * 3600);
                                    //查询所有的自动发圈配置记录
                                    Page<WwCustomer> page = new Page<>();
                                    page.setCurrent(1);//只查第一页
                                    page.setSize(10); //每页查询10个
                                    page.addOrder(OrderItem.asc("id"));//默认id升序
                                    List<WwTagsUserid> wwTagsUseridList = wwTagsUseridMapper.findByList(page, wwTagsUseridQuery);
                                    if (wwTagsUseridList != null) {
                                        for (WwTagsUserid wwTagsUserid : wwTagsUseridList) {
                                            deleteTagForExternalUserid(wwDevice, wwTagsUserid);
                                        }
                                    }
                                }
                            }
                        }
//                    }
                }
            }
        } catch (Exception e) {
            log.info(e.getMessage(), e);
        } finally {
            //删除限流key
            redisTemplate.delete(taskLimitKey);
        }
    }


    private void addTagForExternalUserid(WwDevice wwDevice, WwCustomer wwCustomer){

        if(wwDevice == null){
            return;
        }

        if(wwCustomer == null){
            return;
        }

//        WwCorp wwCorp = wwCorpMapper.selectByCorpId(wwDevice.getMerId(), wwDevice.getCorpId());
//        if(wwCorp == null){
//            return;
//        }
//
//        if(StringUtils.isBlank(wwCorp.getEntId())
//                || StringUtils.isBlank(wwCorp.getEntToken())
//                || StringUtils.isBlank(wwCorp.getEntAesKey())
//                || StringUtils.isBlank(wwCorp.getEntSecret())
//        ){
//            return;
//        }

        Device device = DeviceTools.transDevice(wwDevice);

        int now = DateUtil.getTime();

        //限流判断
        String rateLimitKey = "addTagForExternalUserid-customerId=" + wwCustomer.getId();
        Object object = redisTemplate.opsForValue().get(rateLimitKey);
        if (object == null) {
            redisTemplate.opsForValue().set(rateLimitKey, rateLimitKey, 300, TimeUnit.SECONDS);
        } else {
            return;
        }

        try {
            //内部账号为空才处理
            if (StringUtils.isBlank(wwCustomer.getExternalUserid())) {
                //修改状态
                wwCustomer.setExternalStatus(1);
                wwCustomer.setUpdateTime(DateUtil.getTime());
                wwCustomerMapper.updateExternalUserid(wwCustomer);

                //查询维护内部账号的标签是否存在，如果存在，则不处理
                String tagName = Const.para.TAG_USERID + RandomUtil.randomStringUpper(6);
                WwTagsUserid wwTagsUserid = wwTagsUseridMapper.queryByCustomerIdAndDeviceUniqueId(wwCustomer.getDeviceUniqueId(), wwCustomer.getId());
                if (wwTagsUserid == null) {//未找到标签，则新增加标签，发送创建标签指令
                    wwTagsUserid = new WwTagsUserid();
                    wwTagsUserid.setId(IdWorker.getId());
                    wwTagsUserid.setMerId(wwCustomer.getMerId());
                    wwTagsUserid.setDeviceUniqueId(wwCustomer.getDeviceUniqueId());
                    wwTagsUserid.setCustomerId(wwCustomer.getId());
                    wwTagsUserid.setType(2); //个人标签
                    wwTagsUserid.setTagId(null);
                    wwTagsUserid.setTagName(tagName);
                    wwTagsUserid.setPid(0L);
                    wwTagsUserid.setCorpId(null);
                    wwTagsUserid.setStatus(0); //不可用
                    wwTagsUserid.setSysGroup(1);
                    wwTagsUserid.setCreateTime(now);
                    wwTagsUserid.setUpdateTime(now);
                    wwTagsUseridMapper.insert(wwTagsUserid);

                    log.info("插入添加外部账号标签数据成功，customerId={},tagName={}", wwTagsUserid.getCustomerId(), wwTagsUserid.getTagName());

                    MicaTriggerChangeLabelMsg micaTriggerChangeLabelMsg = new MicaTriggerChangeLabelMsg();
                    micaTriggerChangeLabelMsg.setLabelId(String.valueOf(0));
                    micaTriggerChangeLabelMsg.setLabelName(tagName);
                    micaTriggerChangeLabelMsg.setMessageId(wwTagsUserid.getId());
                    MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerChangeLabelMsg, MicaTriggerType.TRIGGER_CHANGE_LABEL, Functions.fillTriggerMsg(device));
                    sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);

                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            //保存成功之后，手动删除限流redisKey
            redisTemplate.delete(rateLimitKey);
        }
    }

    private void sendTagForExternalUserid(WwDevice wwDevice, WwTagsUserid wwTagsUserid){

        if(wwDevice == null){
            return;
        }

        if(wwTagsUserid == null){
            return;
        }

        Device device = DeviceTools.transDevice(wwDevice);

        int now = DateUtil.getTime();

        //限流判断
        String rateLimitKey = "sendTagForExternalUserid-customerId=" + wwTagsUserid.getId();
        Object object = redisTemplate.opsForValue().get(rateLimitKey);
        if (object == null) {
            redisTemplate.opsForValue().set(rateLimitKey, rateLimitKey, 300, TimeUnit.SECONDS);
        }else{
            return;
        }

        try {

            //内部账号为空才处理
            WwCustomer wwCustomer = wwCustomerMapper.queryById(wwTagsUserid.getCustomerId());
            if(wwCustomer == null || StringUtils.isNotBlank(wwCustomer.getExternalUserid())){
                log.info("-该会员已经有外部账号了，删除该标签-customerId={}", wwTagsUserid.getCustomerId());
                wwTagsUseridMapper.deleteById(wwTagsUserid.getId());
                wwCustomerTagsUseridMapper.deleteByCustomId(wwTagsUserid.getCustomerId());
            }else {
                if (Tools.getInteger(wwTagsUserid.getStatus()).intValue() == 1) { //标签创建完成，则给会员打此标签
                    WwCustomerTagsUserid wwCustomerTagsUserid = wwCustomerTagsUseridMapper.queryByDeviceUniqueIdAndCustomerId(wwDevice.getId(), wwCustomer.getId());
                    if(wwCustomerTagsUserid == null){
                        wwCustomerTagsUserid = new WwCustomerTagsUserid();
                        wwCustomerTagsUserid.setId(IdWorker.getId());
                        wwCustomerTagsUserid.setMerId(wwCustomer.getMerId());
                        wwCustomerTagsUserid.setTagId(wwTagsUserid.getId());
                        wwCustomerTagsUserid.setTagIdStr(wwTagsUserid.getTagId());
                        wwCustomerTagsUserid.setTagName(wwTagsUserid.getTagName());
                        wwCustomerTagsUserid.setDeviceUniqueId(wwDevice.getId());
                        wwCustomerTagsUserid.setCustomerId(wwCustomer.getId());
                        wwCustomerTagsUserid.setCreateTime(now);
                        wwCustomerTagsUserid.setUpdateTime(now);
                        wwCustomerTagsUseridMapper.insert(wwCustomerTagsUserid);

                        log.info("插入会员打外部账号标签数据成功，customerId={},tagName={}", wwCustomerTagsUserid.getCustomerId(), wwCustomerTagsUserid.getTagName());

                        //发送打标签指令
                        MicaTriggerBatchMarkLabelMsg micaTriggerBatchMarkLabelMsg = new MicaTriggerBatchMarkLabelMsg();
                        micaTriggerBatchMarkLabelMsg.setLabelId(wwTagsUserid.getTagId());
                        micaTriggerBatchMarkLabelMsg.setIsCorp(Tools.getInteger(wwTagsUserid.getType()).intValue() == 1 ? true : false); //是否是企业标签
                        micaTriggerBatchMarkLabelMsg.setAddWxIds(Lists.newArrayList(wwCustomer.getWxid()));
                        MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerBatchMarkLabelMsg, MicaTriggerType.TRIGGER_BATCH_MARK_LABEL, Functions.fillTriggerMsg(device));
                        sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC); //存放瞬时消息

                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            //保存成功之后，手动删除限流redisKey
            redisTemplate.delete(rateLimitKey);
        }
    }

    private void deleteTagForExternalUserid(WwDevice wwDevice, WwTagsUserid wwTagsUserid){

        if(wwDevice == null){
            return;
        }

        if(wwTagsUserid == null){
            return;
        }

        Device device = DeviceTools.transDevice(wwDevice);

        int now = DateUtil.getTime();

        //限流判断
        String rateLimitKey = "deleteTagForExternalUserid-wwTagsUserid=" + wwTagsUserid.getId();
        Object object = redisTemplate.opsForValue().get(rateLimitKey);
        if (object == null) {
            redisTemplate.opsForValue().set(rateLimitKey, rateLimitKey, 300, TimeUnit.SECONDS);
        }else{
            return;
        }

        try {

            //删除此标签
            wwTagsUseridMapper.deleteById(wwTagsUserid.getId());

            //删除已经打上的标签
            wwCustomerTagsUseridMapper.deleteByCustomId(wwTagsUserid.getCustomerId());

            //发送删除标签指令
            MicaTriggerChangeLabelMsg micaTriggerChangeLabelMsg = new MicaTriggerChangeLabelMsg();
            micaTriggerChangeLabelMsg.setLabelId(wwTagsUserid.getTagId());
            micaTriggerChangeLabelMsg.setLabelName(wwTagsUserid.getTagName());
            micaTriggerChangeLabelMsg.setMessageId(wwTagsUserid.getId());
            MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerChangeLabelMsg, MicaTriggerType.TRIGGER_DEL_LABEL);
            micaTriggerDto.setMerId(wwDevice.getMerId());
            micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
            micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
            sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);

            log.info("--发送删除更新外部账号标签指令--");

            //内部账号为空才处理
            WwCustomer wwCustomer = wwCustomerMapper.queryById(wwTagsUserid.getCustomerId());
            if(wwCustomer != null && StringUtils.isBlank(wwCustomer.getExternalUserid())){
                wwCustomer.setExternalStatus(0);
                wwCustomer.setUpdateTime(now);
                wwCustomerMapper.updateExternalUserid(wwCustomer);
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            //保存成功之后，手动删除限流redisKey
            redisTemplate.delete(rateLimitKey);
        }
    }

    /**
     * 自动刷新会员的内部账号信息-新增账号时
     *
     * @param wwDevice
     * @return
     */
    @Async("taskExecutorForXxJob")
    public void addTagForExternalUserid(@MerId Long merId, WwDevice wwDevice, WwCustomer wwCustomer) {
        addTagForExternalUserid(wwDevice, wwCustomer);
    }


}
